package com.example.shushiyunsst

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.alibaba.fastjson.JSON
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_USER_INFO
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.signOut
import com.example.wallet.bean.UserInfo
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference
import org.greenrobot.eventbus.EventBus

class UserInfoDataWorker(context: Context, param: WorkerParameters) : Worker(context, param) {
    override fun doWork(): Result {

        val userInfoManager = UserInfoManager.userInfoManager
        val userInfoWrapper = userInfoManager.getUserInfoWrapper()
        val userInfo = userInfoWrapper?.userInfo
        val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
        val maps = mapOf(
            "uid" to userInfo?.uid,
            "deviceToken" to deviceTokens
        )
        RestClient.builder()
            .url(R.string.queryUserByUid)
            .raw(JSON.toJSONString(maps))
            .success {
                Log.d("onSupportVisible", "queryUserByUid: $it")
                val parse = JSON.parseObject(it)
                val userInfoStr = parse["userInfo"]
                val userInfoNew = JSON.parseObject(userInfoStr.toString(), UserInfo::class.java)
                userInfoWrapper?.userInfo = userInfoNew
                userInfoNew.UserInfoTemple=JSON.toJSONString(userInfoStr)
                userInfoManager.saveUserInfoWrapper(userInfoWrapper)

                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_USER_INFO))

            }.failure {
                normalShortToast(AppGlobals.getApplication(),R.string.user_info_failed)
//                Toast.makeText(AppGlobals.getApplication(), "获取用户信息失败", Toast.LENGTH_SHORT).show()
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_USER_INFO))

            }.error { code, msg ->
                if(code ==502){
                    signOut()
                }
                normalShortToast(AppGlobals.getApplication(), msg)
//                Toast.makeText(AppGlobals.getApplication(), msg, Toast.LENGTH_SHORT).show()
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_USER_INFO))
            }
            .build()
            .post()

         return Result.success()
    }

//    private fun signOut() {
//        UserInfoManager.userInfoManager.signOutUserInfoWrapper()
//        MainActivity.entry(com.example.wallet.global.AppGlobals.getApplication())
//    }
}